package gecko.dk;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * 设置主板上报服务器IP指令
 *
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
public class InstrReportServer extends Instr {

    /**
     * 创建指令
     *
     * @param devSN      设备序列号
     * @param serverIP   UDP服务器IP
     * @param serverPort UDP服务器端口
     * @param periodSec  上报周期
     */
    public InstrReportServer(int devSN, String serverIP, short serverPort, int periodSec) {
        super(
                (byte) 0x90,
                devSN,
                0,
                data(serverIP, serverPort, periodSec)
        );
    }

    /**
     * 创建指令；上报周期为：当发生新数据记录时才上报；
     *
     * @param devSN      设备序列号
     * @param serverIP   UDP服务器IP
     * @param serverPort UDP服务器端口
     */
    public InstrReportServer(int devSN, String serverIP, short serverPort) {
        this(devSN, serverIP, serverPort, 0);
    }

    public static InstrReportServer create(int devSN, String serverIP, short serverPort) {
        return new InstrReportServer(devSN, serverIP, serverPort);
    }

    public static InstrReportServer create(int devSN, String serverIP, short serverPort, int periodSec) {
        return new InstrReportServer(devSN, serverIP, serverPort, periodSec);
    }

    private static byte[] data(String serverIP, short serverPort, int periodSec) {
        periodSec = Math.max(0, Math.min(periodSec, 10));
        final ByteBuffer data = makeBuffer(DATA_SIZE);
        data.order(ByteOrder.LITTLE_ENDIAN);
        data.put(ip2Bytes(serverIP));
        data.putShort(serverPort);
        data.put((byte) periodSec);
        return data.array();
    }
}
